package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableRowSorter;

public class Area extends javax.swing.JInternalFrame {
    private int codigo_area;
    private String id_bitacora;
    private boolean nuevo;
    private JFileChooser selector;
    public Area() {
        initComponents();
        this.setLocation(new Point(70,0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("areas.xls"));
        Bloquear(true);
        BloquearTexto(true);
        CargarAreas();
        codigo_area=-1;
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }
    private void Bloquear(boolean estado){
        jbtnNuevo.setEnabled(estado);
        jbtnGuardar.setEnabled(!estado);
        jbtnModificar.setEnabled(estado);
        jbtnEliminar.setEnabled(estado);
        jbtnCancelar.setEnabled(!estado);
        jtblArea.setEnabled(estado);
    }
    private void BloquearTexto(boolean estado){
        jtfNombreArea.setEditable(!estado);
    }
    private void Limpiar(){
        jtfNombreArea.setText("");
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jtfNombreArea = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnEliminar = new javax.swing.JButton();
        jbtnModificar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jbtnNuevo = new javax.swing.JButton();
        jbtnExportar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtblArea = new javax.swing.JTable();

        setClosable(true);
        setTitle("Administración de Áreas");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/area.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Area"));

        jLabel10.setText("Nombre:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_eliminar.png"))); // NOI18N
        jbtnEliminar.setToolTipText("Eliminar");
        jbtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminarActionPerformed(evt);
            }
        });

        jbtnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_modificar.png"))); // NOI18N
        jbtnModificar.setToolTipText("Modificar");
        jbtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnModificarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jbtnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnNuevo.setToolTipText("Nuevo");
        jbtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jScrollPane3.setViewportView(jtblArea);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jtfNombreArea, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(jtfNombreArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void CargarAreas(){
        Util.CargarTabla(jtblArea,"SELECT id_area,nombre FROM Area",new String[]{"Id","Nombre"});
        Util.AlinearColumnas(jtblArea,SwingConstants.CENTER);
        Util.OcultarColumna(jtblArea,0);
        jtblArea.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla)jtblArea.getModel()));
    }
    private void SeleccionarDatos(){
        int fila=jtblArea.getSelectedRow();
        if(fila!=-1){
            codigo_area=(int)jtblArea.getValueAt(fila,0);
            jtfNombreArea.setText((String)jtblArea.getValueAt(fila,1));
        }
    }
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        Limpiar();
        Bloquear(true);
        BloquearTexto(true);
        SeleccionarDatos();
        jtfNombreArea.setText("");
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminarActionPerformed
        if(jtblArea.getSelectedRow()!=-1){
            if(JOptionPane.showConfirmDialog(null,"¿Esta seguro de eliminar el area y todo lo relacionado con ella?","Administración de Areas",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                if(Conexion.EjecutarConsulta("DELETE FROM area Where id_area="+jtblArea.getValueAt(jtblArea.getSelectedRow(),0))){
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Eliminar Area: "+Util.ComponerTexto(jtblArea.getValueAt(jtblArea.getSelectedRow(),1).toString()));
                    CargarAreas();
                    jtfNombreArea.setText("");
                    JOptionPane.showMessageDialog(null,"¡Area Eliminada!","Administración de Areas",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }
        else
            JOptionPane.showMessageDialog(null,"Debe seleccionar un area.","Administración de Areas",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnEliminarActionPerformed
    private void jbtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnModificarActionPerformed
        if(jtblArea.getSelectedRow()>-1){
            jtfNombreArea.setText((String)jtblArea.getValueAt(jtblArea.getSelectedRow(),1));
            Bloquear(false);
            BloquearTexto(false);
            nuevo=false;
        }
    }//GEN-LAST:event_jbtnModificarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if(nuevo && !jtfNombreArea.getText().equals("")){
            if(Conexion.EjecutarConsulta("INSERT INTO area(nombre) VALUES('"+Util.ComponerTexto(jtfNombreArea.getText())+"');")){
                if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Guardar Area: "+Util.ComponerTexto(jtfNombreArea.getText()));
                CargarAreas();
                jtfNombreArea.setText("");
                JOptionPane.showMessageDialog(null,"¡Area Agregada!","Administración de Areas",JOptionPane.INFORMATION_MESSAGE);
            }
            else
            JOptionPane.showMessageDialog(null,"No se pudo agregar el area.","Administración de Areas",JOptionPane.ERROR_MESSAGE);
        }
        else{
            if(jtblArea.getSelectedRow()!=-1 && !jtfNombreArea.getText().equals("") ){
                int id=(int)jtblArea.getValueAt(jtblArea.getSelectedRow(),0);
                if(Conexion.EjecutarConsulta("UPDATE area SET nombre='"+Util.ComponerTexto(jtfNombreArea.getText())+"' WHERE id_area="+id)){
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Modificar Area: "+Util.ComponerTexto(jtfNombreArea.getText()));
                    CargarAreas();
                    JOptionPane.showMessageDialog(null,"¡Area Modificada!","Administración de Areas",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                JOptionPane.showMessageDialog(null,"No se pudo modificar el Area","Administración de Areas",JOptionPane.ERROR_MESSAGE);
            }
            else
            JOptionPane.showMessageDialog(null,"Debe seleccionar una area","Administración de Areas",JOptionPane.WARNING_MESSAGE);
        }
        Bloquear(true);
        BloquearTexto(true);
        Limpiar();
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void jbtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoActionPerformed
        Bloquear(false);
        BloquearTexto(false);
        Limpiar();
        jtblArea.clearSelection();
        nuevo=true;
    }//GEN-LAST:event_jbtnNuevoActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing
    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblArea.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblArea,archivo_excel,"Áreas")){
                        case OK:
                            JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                            Desktop.getDesktop().open(archivo_excel);
                            break;
                        case CANCELADO:
                            break;
                        case ERROR:
                            JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                            break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel10;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnEliminar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnModificar;
    private javax.swing.JButton jbtnNuevo;
    private javax.swing.JTable jtblArea;
    private javax.swing.JTextField jtfNombreArea;
    // End of variables declaration//GEN-END:variables
}